<template>
  <div class="inbound-order-detail">
    <a-card :bordered="false" title="入库单基本信息">
      <a-descriptions bordered :column="3">
        <a-descriptions-item label="入库单号">{{ inboundOrder.inboundNo }}</a-descriptions-item>
        <a-descriptions-item label="业务类型">
          <j-dict-tag :value="inboundOrder.businessType" dictCode="inventory_business_type"/>
        </a-descriptions-item>
        <a-descriptions-item label="业务单号">{{ inboundOrder.businessNo }}</a-descriptions-item>
        <a-descriptions-item label="批次号">{{ inboundOrder.batchNo }}</a-descriptions-item>
        <a-descriptions-item label="供应商">{{ inboundOrder.supplier }}</a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getStatusColor(inboundOrder.status)">
            <j-dict-tag :value="inboundOrder.status" dictCode="inbound_order_status"/>
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="计划入库时间">{{ inboundOrder.planInboundTime }}</a-descriptions-item>
        <a-descriptions-item label="实际入库时间">{{ inboundOrder.actualInboundTime || '-' }}</a-descriptions-item>
        <a-descriptions-item label="创建人">{{ inboundOrder.createBy }}</a-descriptions-item>
        <a-descriptions-item label="总计划入库数量">{{ inboundOrder.totalPlanQuantity }}</a-descriptions-item>
        <a-descriptions-item label="总实际入库数量">{{ inboundOrder.totalActualQuantity || 0 }}</a-descriptions-item>
        <a-descriptions-item label="总成本">{{ inboundOrder.totalCost }}</a-descriptions-item>
        <a-descriptions-item label="备注" :span="3">{{ inboundOrder.remark || '-' }}</a-descriptions-item>
      </a-descriptions>
    </a-card>
    
    <a-card :bordered="false" title="入库单明细" style="margin-top: 16px;">
      <div class="table-operations" style="margin-bottom: 16px;">
        <a-button type="primary" icon="plus" @click="handleAddDetail" v-if="inboundOrder.status === 1">添加明细</a-button>
        <a-button icon="reload" @click="loadDetailList">刷新</a-button>
      </div>
      
      <a-table
        :columns="columns"
        :dataSource="detailList"
        :pagination="false"
        :loading="loading"
        rowKey="id"
        size="middle">
        <template slot="materialTypeSlot" slot-scope="text">
          <j-dict-tag :value="text" dictCode="material_type"/>
        </template>
        <template slot="warehouseSlot" slot-scope="text, record">
          {{ record.planWarehouseName || '-' }}
        </template>
        <template slot="locationSlot" slot-scope="text, record">
          {{ record.planLocationName || '-' }}
        </template>
        <template slot="actualWarehouseSlot" slot-scope="text, record">
          {{ record.actualWarehouseName || '-' }}
        </template>
        <template slot="actualLocationSlot" slot-scope="text, record">
          {{ record.actualLocationName || '-' }}
        </template>
        <template slot="action" slot-scope="text, record">
          <a @click="handleConfirmInbound(record)" v-if="inboundOrder.status !== 4 && (!record.actualQuantity || record.actualQuantity < record.planQuantity)">确认入库</a>
          <a-divider type="vertical" v-if="inboundOrder.status === 1"/>
          <a @click="handleEditDetail(record)" v-if="inboundOrder.status === 1">编辑</a>
          <a-divider type="vertical" v-if="inboundOrder.status === 1"/>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteDetail(record.id)" v-if="inboundOrder.status === 1">
            <a>删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
    
    <!-- 确认入库弹窗 -->
    <a-modal
      title="确认入库"
      :visible="confirmVisible"
      @ok="confirmInbound"
      @cancel="confirmVisible = false"
      :confirmLoading="confirmLoading">
      <a-form :form="confirmForm">
        <a-form-item label="物料名称" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <a-input :value="currentDetail.materialName" disabled />
        </a-form-item>
        <a-form-item label="计划入库数量" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <a-input :value="currentDetail.planQuantity + ' ' + currentDetail.unit" disabled />
        </a-form-item>
        <a-form-item label="已入库数量" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <a-input :value="(currentDetail.actualQuantity || 0) + ' ' + currentDetail.unit" disabled />
        </a-form-item>
        <a-form-item label="实际入库仓库" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <j-select-warehouse
            v-decorator="['actualWarehouseId', {rules: [{required: true, message: '请选择实际入库仓库'}]}]"
            :defaultValue="currentDetail.planWarehouseId"
            @change="handleActualWarehouseChange" />
        </a-form-item>
        <a-form-item label="实际入库库位" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <j-select-warehouse-location
            v-decorator="['actualLocationId', {rules: [{required: true, message: '请选择实际入库库位'}]}]"
            :warehouse-id="actualWarehouseId"
            :defaultValue="currentDetail.planLocationId" />
        </a-form-item>
        <a-form-item label="实际入库数量" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <a-input-number
            v-decorator="['actualQuantity', {rules: [{required: true, message: '请输入实际入库数量'}]}]"
            style="width: 100%"
            :min="0.01"
            :max="currentDetail.planQuantity - (currentDetail.actualQuantity || 0)"
            :precision="2"
            :step="1" />
        </a-form-item>
        <a-form-item label="备注" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <a-textarea
            v-decorator="['remark']"
            :rows="3"
            placeholder="请输入备注" />
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 编辑明细弹窗 -->
    <a-modal
      title="编辑明细"
      :visible="editVisible"
      @ok="saveDetail"
      @cancel="editVisible = false"
      :confirmLoading="editLoading">
      <a-form :form="editForm">
        <a-form-item label="物料" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <j-select-material
            v-decorator="['materialId', {rules: [{required: true, message: '请选择物料'}]}]"
            @change="handleMaterialChange" />
        </a-form-item>
        <a-form-item label="仓库" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <j-select-warehouse
            v-decorator="['planWarehouseId', {rules: [{required: true, message: '请选择仓库'}]}]"
            @change="handleWarehouseChange" />
        </a-form-item>
        <a-form-item label="库位" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <j-select-warehouse-location
            v-decorator="['planLocationId', {rules: [{required: true, message: '请选择库位'}]}]"
            :warehouse-id="editWarehouseId" />
        </a-form-item>
        <a-form-item label="计划入库数量" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <a-input-number
            v-decorator="['planQuantity', {rules: [{required: true, message: '请输入计划入库数量'}]}]"
            style="width: 100%"
            :min="0.01"
            :precision="2"
            :step="1" />
        </a-form-item>
        <a-form-item label="单位成本" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <a-input-number
            v-decorator="['unitCost', {rules: [{required: true, message: '请输入单位成本'}]}]"
            style="width: 100%"
            :min="0"
            :precision="2"
            :step="0.01" />
        </a-form-item>
        <a-form-item label="预警上限" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <a-input-number
            v-decorator="['upperLimit']"
            style="width: 100%"
            :min="0"
            :precision="2"
            :step="0.01" />
        </a-form-item>
        <a-form-item label="预警下限" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <a-input-number
            v-decorator="['lowerLimit']"
            style="width: 100%"
            :min="0"
            :precision="2"
            :step="0.01" />
        </a-form-item>
        <a-form-item label="备注" :labelCol="{span: 6}" :wrapperCol="{span: 14}">
          <a-textarea
            v-decorator="['remark']"
            :rows="3"
            placeholder="请输入备注" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { getAction, postAction, putAction, deleteAction } from '@/api/manage'
import JDictTag from '@/components/dict/JDictTag'
import JSelectMaterial from '@/components/jeecgbiz/JSelectMaterial'
import JSelectWarehouse from '@/components/jeecgbiz/JSelectWarehouse'
import JSelectWarehouseLocation from '@/components/jeecgbiz/JSelectWarehouseLocation'

export default {
  name: 'InboundOrderDetail',
  components: {
    JDictTag,
    JSelectMaterial,
    JSelectWarehouse,
    JSelectWarehouseLocation
  },
  props: {
    inboundOrderId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      inboundOrder: {},
      detailList: [],
      loading: false,
      columns: [
        {
          title: '物料编码',
          dataIndex: 'materialCode',
          width: 120
        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
          width: 150
        },
        {
          title: '物料类型',
          dataIndex: 'materialType',
          width: 100,
          scopedSlots: { customRender: 'materialTypeSlot' }
        },
        {
          title: '规格',
          dataIndex: 'specification',
          width: 120
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: 80
        },
        {
          title: '计划入库仓库',
          dataIndex: 'planWarehouseId',
          width: 120,
          scopedSlots: { customRender: 'warehouseSlot' }
        },
        {
          title: '计划入库库位',
          dataIndex: 'planLocationId',
          width: 120,
          scopedSlots: { customRender: 'locationSlot' }
        },
        {
          title: '计划入库数量',
          dataIndex: 'planQuantity',
          width: 120
        },
        {
          title: '实际入库仓库',
          dataIndex: 'actualWarehouseId',
          width: 120,
          scopedSlots: { customRender: 'actualWarehouseSlot' }
        },
        {
          title: '实际入库库位',
          dataIndex: 'actualLocationId',
          width: 120,
          scopedSlots: { customRender: 'actualLocationSlot' }
        },
        {
          title: '实际入库数量',
          dataIndex: 'actualQuantity',
          width: 120
        },
        {
          title: '单位成本',
          dataIndex: 'unitCost',
          width: 100
        },
        {
          title: '总成本',
          dataIndex: 'totalCost',
          width: 100
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 150,
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 确认入库相关
      confirmVisible: false,
      confirmLoading: false,
      confirmForm: this.$form.createForm(this),
      currentDetail: {},
      actualWarehouseId: '',
      // 编辑明细相关
      editVisible: false,
      editLoading: false,
      editForm: this.$form.createForm(this),
      editWarehouseId: '',
      editDetailId: ''
    }
  },
  created() {
    this.loadInboundOrder()
  },
  methods: {
    // 加载入库单信息
    loadInboundOrder() {
      this.loading = true
      getAction('/wms/inboundOrder/queryById', { id: this.inboundOrderId }).then(res => {
        if (res.success) {
          this.inboundOrder = res.result
          this.loadDetailList()
        } else {
          this.$message.error(res.message || '获取入库单信息失败')
        }
      }).finally(() => {
        this.loading = false
      })
    },
    
    // 加载明细列表
    loadDetailList() {
      this.loading = true
      getAction('/wms/inboundOrder/queryDetailList', { inboundOrderId: this.inboundOrderId }).then(res => {
        if (res.success) {
          this.detailList = res.result || []
        } else {
          this.$message.error(res.message || '获取入库单明细失败')
        }
      }).finally(() => {
        this.loading = false
      })
    },
    
    // 获取状态颜色
    getStatusColor(status) {
      switch (parseInt(status)) {
        case 1: return 'blue'    // 待入库
        case 2: return 'green'   // 已入库
        case 3: return 'orange'  // 部分入库
        case 4: return 'red'     // 已取消
        default: return 'default'
      }
    },
    
    // 添加明细
    handleAddDetail() {
      this.editDetailId = ''
      this.editForm.resetFields()
      this.editVisible = true
    },
    
    // 编辑明细
    handleEditDetail(record) {
      this.editDetailId = record.id
      this.editWarehouseId = record.planWarehouseId
      
      this.$nextTick(() => {
        this.editForm.setFieldsValue({
          materialId: record.materialId,
          planWarehouseId: record.planWarehouseId,
          planLocationId: record.planLocationId,
          planQuantity: record.planQuantity,
          unitCost: record.unitCost,
          upperLimit: record.upperLimit,
          lowerLimit: record.lowerLimit,
          remark: record.remark
        })
      })
      
      this.editVisible = true
    },
    
    // 删除明细
    handleDeleteDetail(id) {
      // 实际项目中应该调用后端API删除明细
      this.$message.success('删除成功')
      this.loadDetailList()
    },
    
    // 保存明细
    saveDetail() {
      this.editForm.validateFields((err, values) => {
        if (err) return
        
        this.editLoading = true
        
        // 构建保存数据
        const detail = {
          ...values,
          inboundOrderId: this.inboundOrderId
        }
        
        if (this.editDetailId) {
          detail.id = this.editDetailId
        }
        
        // 实际项目中应该调用后端API保存明细
        setTimeout(() => {
          this.editLoading = false
          this.editVisible = false
          this.$message.success('保存成功')
          this.loadDetailList()
        }, 500)
      })
    },
    
    // 确认入库
    handleConfirmInbound(record) {
      this.currentDetail = record
      this.actualWarehouseId = record.planWarehouseId
      
      this.$nextTick(() => {
        this.confirmForm.setFieldsValue({
          actualWarehouseId: record.planWarehouseId,
          actualLocationId: record.planLocationId,
          actualQuantity: record.planQuantity - (record.actualQuantity || 0)
        })
      })
      
      this.confirmVisible = true
    },
    
    // 提交确认入库
    confirmInbound() {
      this.confirmForm.validateFields((err, values) => {
        if (err) return
        
        this.confirmLoading = true
        
        // 构建参数
        const params = {
          id: this.inboundOrderId,
          detailId: this.currentDetail.id,
          ...values
        }
        
        postAction('/wms/inboundOrder/confirmInbound', params).then(res => {
          if (res.success) {
            this.$message.success('确认入库成功')
            this.confirmVisible = false
            this.loadInboundOrder() // 重新加载入库单和明细
          } else {
            this.$message.error(res.message || '确认入库失败')
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      })
    },
    
    // 物料选择变更
    handleMaterialChange(value, materials) {
      if (materials && materials.length > 0) {
        const material = materials[0]
        this.editForm.setFieldsValue({
          unitCost: material.unitCost || 0
        })
      }
    },
    
    // 仓库选择变更
    handleWarehouseChange(value) {
      this.editWarehouseId = value
      this.editForm.setFieldsValue({
        planLocationId: undefined
      })
    },
    
    // 实际入库仓库变更
    handleActualWarehouseChange(value) {
      this.actualWarehouseId = value
      this.confirmForm.setFieldsValue({
        actualLocationId: undefined
      })
    }
  }
}
</script>

<style scoped>
.inbound-order-detail {
  background-color: #f0f2f5;
  padding: 24px;
}
</style> 